package com.yxsk.relay.job.endpoint.combine.loader;

import com.alibaba.fastjson.JSONObject;
import com.yxsk.relay.job.component.common.utils.Assert;
import com.yxsk.relay.job.endpoint.combine.exception.resource.ResourceLoadException;
import com.yxsk.relay.job.endpoint.combine.exception.resource.ResourceNotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

/**
 * @Description
 * @Author 11376
 * @CreateTime 2019/9/9 16:05
 */
@Slf4j
public class ClassPathResourceLoader implements ResourceLoader {

    public static final String CLASSPATH_PREFIX = "classpath:";

    @Override
    public <T> T load(String path, Class<T> resourceType) {
        Assert.hasLength(path, "Load resource path not be empty.");

        String loadPath = path;
        if (path.startsWith(CLASSPATH_PREFIX)) {
            loadPath = path.substring(CLASSPATH_PREFIX.length());
            if (StringUtils.isEmpty(loadPath)) {
                throw new IllegalArgumentException("Load path error(" + path + ")");
            }
        }

        if (loadPath.endsWith(".yml") || loadPath.endsWith(".yaml")) {
            try {
                // 读取 yml
                Yaml yaml = new Yaml();
                return yaml.loadAs(getClassPathResourceInputStream(loadPath), resourceType);
            } catch (IOException e) {
                throw new ResourceLoadException(e);
            }
        } else if (loadPath.endsWith(".json")) {
            // 读取 json
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(getClassPathResourceInputStream(loadPath)));
                StringBuilder json = new StringBuilder();
                String buff;
                while ((buff = reader.readLine()) != null) {
                    json.append(buff).append("\n");
                }
                return JSONObject.parseObject(json.toString(), resourceType);
            } catch (IOException e) {
                throw new ResourceLoadException(e);
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        log.error("Close resource file error, file: " + loadPath, e);
                    }
                }
            }
        }
        throw new ResourceLoadException("Unsupported resource file type, path: " + path);
    }

    private InputStream getClassPathResourceInputStream(String path) throws IOException {
        URL resource = ClassPathResourceLoader.class.getClassLoader().getResource(path);
        if (resource == null) {
            throw new ResourceNotFoundException("Can't found classpath resource file: " + path);
        }
        return resource.openStream();
    }

}
